package com.dxb.test.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName：com.dxb.test.thread.ConditionABC <br>
 * Description：reentrantLock condition <br>
 *
 * @author 戴晓波 <br>
 * Date 2022/2/14/014 13:31 <br>
 * @version v1.0 <br>
 */
public class ConditionABC {
    ReentrantLock lock = new ReentrantLock();
    int num = 0;

    void print(int index, Condition current, Condition next) {
        for (int i = 0; i < 10; i++) {
            lock.lock();
            try {
                while (num % 3 != index) {
                    current.await();
                }
                num++;
                System.out.println(Thread.currentThread().getName());
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        ConditionABC lock = new ConditionABC();
        Condition condition0 = lock.lock.newCondition();
        Condition condition1 = lock.lock.newCondition();
        Condition condition2 = lock.lock.newCondition();
        new Thread(() -> lock.print(0, condition0, condition1), "A").start();
        new Thread(() -> lock.print(1, condition1, condition2), "B").start();
        new Thread(() -> lock.print(2, condition2, condition0), "C").start();
    }
}
